import './App.scss';
import {
  createBrowserRouter,
  createRoutesFromElements,
  Navigate,
  Route,
  RouterProvider,
} from 'react-router-dom';
import Login from './pages/login';
import MainTemplate from './layouts/main-template';
import React, { useEffect, useState } from 'react';
import { useSelector, shallowEqual } from 'react-redux';
import { IRootReducerState } from './store/root-reducer';
import SubTemplate from './layouts/ sub-template';

const Home = React.lazy(() => import('./pages/home'));

const App = () => {
  const [dynamicRoutes, setDynamicRoutes] = useState<
    { path: string; template: any }[]
  >([]);

  const { auth } = useSelector<IRootReducerState, any>(
    (state) => ({ auth: state.auth }),
    shallowEqual
  );

  console.log("dynamicRoutes",dynamicRoutes,auth?.userToken)

  useEffect(() => {
    new Promise((resolve) =>
      setTimeout(() => {
        setDynamicRoutes([
          {
            path: 'main/*',
            template: MainTemplate,
          },
          {
            path: 'operation/*',
            template: MainTemplate,
          },
        ]);
      }, 1000)
    );
  }, []);

  const router = createBrowserRouter(
    createRoutesFromElements(
      <Route>
        {auth?.userToken && (
          <Route
            path='/'
            element={
              <React.Suspense fallback={<div className='navigation-loader' />}>
                <Home />
              </React.Suspense>
            }>
            {dynamicRoutes.map((rt) => (
              <Route key={rt.path} path={rt.path} element={<rt.template />} />
            ))}
                       <Route
              path='sub'
              element={
                <React.Suspense
                  fallback={<div className='navigation-loader' />}>
                  <SubTemplate />
                </React.Suspense>
              }
            />

            <Route index element={<Navigate to='operation' />} />
          </Route>
        )}
        <Route path='/login' element={<Login />} />
        <Route
          path='*'
          element={
            dynamicRoutes.length === 0 ? (
              <div>loading routes</div>
            ) : auth?.userToken? (
              <div>not found</div>
            ) : (
              <Navigate
                to='/login'
                state={{ returnUrl: location.pathname }}
                replace
              />
            )
          }
        />
      </Route>
    ),
    //@ts-ignore
    { basename: import.meta.env.BASE_URL }
  );

  return <RouterProvider router={router} />;
};

export default App;
